package com.gexin.controller.xapp.agent;

import com.gexin.common.AppGlobal;
import com.gexin.common.kusy.KusyUtil;
import com.gexin.common.utils.RedisLockTool;
import com.gexin.model.agent.Agent;
import com.gexin.model.agent.AgentAccountLog;
import com.gexin.weixin.kit.WeiXinUtils;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.kit.HttpKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.weixin.sdk.kit.PaymentKit;

import java.math.BigDecimal;
import java.util.*;


@ControllerBind(controllerKey = "/xapp/agent/notify")
public class AgentPayNotifyController extends Controller {
	static final Log log = Log.getLog(AgentPayNotifyController.class);
	@Before(Tx.class)
	public void index(){
		String lock_key = "cache:order:lock:";
		try {//这里是回调
			log.info("微信支付成功回调=====");
			SortedMap<String, String> params = new TreeMap<>();
			Enumeration<String> paraNames = getParaNames();
			System.err.println("=======================");
			for (Enumeration<String> e = paraNames; e.hasMoreElements(); ) {
				String thisName = e.nextElement().toString();
				String thisValue = getPara(thisName);
				if(AppGlobal.dev_Mode){
					System.err.println("param的key:" + thisName + "--------------param的value:" + thisValue);
				}
				params.put(thisName, thisValue);
			}
			System.err.println("=======================");

			String sign = KusyUtil.createSign(params, KusyUtil.Sign_Key);
			if (sign.equals(getPara("sign"))) {
				// 如果验证码成功 要判断订单别重复提交了
				String out_trade_no = getPara("mch_orderid");
				String transaction_id = getPara("orderid");//支付系统id
//				String transaction_id = getPara("trade_no");//微信交易单号
				BigDecimal pay_money = new BigDecimal(getPara("pri_paymoney"));//支付金额
				log.info(String.format("订单APP支付成功通知，内部ID:%s,微信支付ID:%s,支付金额：%s分", out_trade_no, transaction_id, pay_money));
				lock_key = lock_key + out_trade_no;
				boolean lock_get_state = RedisLockTool.getLock(lock_key, 5000);  //获取锁
				if (lock_get_state) {
					AgentAccountLog accountLog = AgentAccountLog.dao.findById(out_trade_no);
					accountLog.setStatus(AgentAccountLog.STATUS_SUCCESS);
					accountLog.setTransactionId(transaction_id);
					boolean update = accountLog.update();
					if (update) {
						Agent agent = Agent.dao.findById(accountLog.getAgentId());
						agent.setCashDepositState(Agent.CASH_DEPOSIT_YIZHIFU);
						agent.setCashDepositTime(new Date());
						boolean updateAgent = agent.update();
						if(updateAgent){
							//处理成功
							renderText(WeiXinUtils.wxPayResponse("SUCCESS", ""));
						}else{
							log.error("订单修改保存失败! " + out_trade_no + "   transaction_id:" + transaction_id+",代理商信息保存失败");
							renderText(WeiXinUtils.wxPayResponse("FAIL", ""));
						}
					} else {
						log.error("订单修改保存失败! " + out_trade_no + "   transaction_id:" + transaction_id+",流水信息保存失败");
						renderText(WeiXinUtils.wxPayResponse("FAIL", ""));
					}
				} else {
					renderText(WeiXinUtils.wxPayResponse("FAIL", ""));
				}
			}else{
				renderText(WeiXinUtils.wxPayResponse("FAIL", ""));
			}
		} catch (Exception e) {
			log.error("支付回调发生异常错误:", e.fillInStackTrace());
			renderText(WeiXinUtils.wxPayResponse("FAIL", ""));
		} finally {
			RedisLockTool.releaseLock(lock_key);//释放锁
		}
	}


	@Before(Tx.class)
	public void parseJson(){
 		String lock_key = "cache:order:lock:";
		try {//这里是回调
			String xmlMsg = HttpKit.readData(getRequest());
			log.info("订单付款APP微信支付成功回调=====" + xmlMsg);
			Map<String, String> map = PaymentKit.xmlToMap(xmlMsg);
			if (map != null && map.get("result_code").toString().trim().equals("SUCCESS")) {
				// 如果验证码成功 要判断订单别重复提交了
				String out_trade_no = map.get("out_trade_no");// 支付订单ID
				String transaction_id = map.get("transaction_id");//微信的流水ID
				Integer total_fee = Integer.parseInt(map.get("total_fee"));// 支付多少钱
				log.info(String.format("订单APP支付成功通知，内部ID:%s,微信支付ID:%s,支付金额：%s分", out_trade_no, transaction_id, total_fee));
				lock_key = lock_key + out_trade_no;
				boolean lock_get_state = RedisLockTool.getLock(lock_key, 5000);  //获取锁
				if (lock_get_state) {
					AgentAccountLog accountLog = AgentAccountLog.dao.findById(out_trade_no);
					accountLog.setStatus(AgentAccountLog.STATUS_SUCCESS);
					boolean update = accountLog.update();
					if (update) {
						Agent agent = Agent.dao.findById(accountLog.getAgentId());
						agent.setCashDepositState(Agent.CASH_DEPOSIT_YIZHIFU);
						agent.setCashDepositTime(new Date());
						boolean updateAgent = agent.update();
						if(updateAgent){
							//处理成功
							renderText(WeiXinUtils.wxPayResponse("SUCCESS", ""));
						}else{
							log.error("订单修改保存失败! " + out_trade_no + "   transaction_id:" + transaction_id+",代理商信息保存失败");
							renderText(WeiXinUtils.wxPayResponse("FAIL", ""));
						}
					} else {
						log.error("订单修改保存失败! " + out_trade_no + "   transaction_id:" + transaction_id+",流水信息保存失败");
						renderText(WeiXinUtils.wxPayResponse("FAIL", ""));
					}
				} else {
					renderText(WeiXinUtils.wxPayResponse("FAIL", ""));
				}
			}else{
				renderText(WeiXinUtils.wxPayResponse("FAIL", ""));
			}
		} catch (Exception e) {
			log.error("支付回调发生异常错误:", e.fillInStackTrace());
			renderText(WeiXinUtils.wxPayResponse("FAIL", ""));
		} finally {
			RedisLockTool.releaseLock(lock_key);//释放锁
		}
	}

}
